package com.obrempon.credit.market.ui.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import com.google.android.material.tabs.TabLayout
import com.obrempon.credit.market.ObremponApp
import com.obrempon.credit.market.R
import com.obrempon.credit.market.common.CommonDialog
import com.obrempon.credit.market.databinding.ObremponBirthdayDialogBinding
import com.obrempon.credit.market.databinding.ObremponBirthdayDialogMonthItemBinding
import com.obrempon.credit.market.event.ObremponEventPointType
import com.obrempon.credit.market.ui.adapter.ObremponBirthdayDayApt
import com.obrempon.credit.market.ui.adapter.ObremponBirthdayWeekApt
import com.obrempon.credit.market.utils.ObremponDensityUtil
import com.obrempon.credit.market.utils.decoration.GridSpacingItemDecoration
import com.obrempon.credit.market.utils.helper.ObremponDateHelper
import com.obrempon.credit.market.weight.font.RobotoMediumTextView
import com.obrempon.module.adapter.ObremponOnItemChildClickListener
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.Calendar

/**
 * Author : wwdeng
 * Date : 2024/5/23 15:44
 * <p>
 * 每天进步一点点
 * <p>
 * Desc : 流程选择出生日期
 */
class ObremponBirthdayDialog: CommonDialog {
    private lateinit var binding: ObremponBirthdayDialogBinding
    private var mCallback: IDialogCallback? = null
    //开始选择时间
    private var startTime = 0L;
    //事件备注
    private var eventRemark = ""
    /* 周 */
    private var weekAdapter: ObremponBirthdayWeekApt? = null
    /* 日期 */
    private var dayAdapter: ObremponBirthdayDayApt? = null

    //年
    private var showYear = ObremponDateHelper.getCurtYear()
    //月
    private var isInit = true
    private var showMonth = ObremponDateHelper.getCurtMonth()
    //日
    private var showDay = ObremponDateHelper.getCurtDay()

    constructor(context: Context) : super(context) {}
    constructor(context: Context, callback: IDialogCallback?) : super(context) {
        mCallback = callback
    }

    constructor(context: Context, remark: String = "",callback: IDialogCallback?) : super(context) {
        mCallback = callback
        eventRemark = remark
    }

    /**
     * 设置点击回调
     */
    fun setOnClick(callback: IDialogCallback){
        this.mCallback = callback
    }

    override fun initObremponWindow() {
        val params = window!!.attributes
        params.width = ObremponApp.app.getPhoneWidth()
        params.height = WindowManager.LayoutParams.WRAP_CONTENT
        window!!.attributes = params
        window!!.setWindowAnimations(R.style.dialog_slide_anim) //修改动画样式
        window!!.setGravity(Gravity.BOTTOM)
    }

    override fun takeObremponRootView(): View {
        binding = ObremponBirthdayDialogBinding.inflate(LayoutInflater.from(context))
        return binding.root
    }

    override fun initObremponView() {
        initBirthdayMonthTabLayout()
        initBirthdayWeekListView()
        initBirthdayDayListView()
    }

    override fun initObremponListener() {
        setOnClickListener(binding.buttonDone)
        //上一年
        binding.imgLastYear.setOnClickListener {
            showYear--
            showYear()
            showDay()
        }
        //下一年
        binding.imgNextYear.setOnClickListener {
            if (showYear >= ObremponDateHelper.getCurtYear()){
                return@setOnClickListener
            }
            showYear++
            showYear()
            showDay()
        }
    }

    override fun takeObremponData() {
        showYear()
        showMonth()
        showDay()
    }

    @SuppressLint("SimpleDateFormat")
    override fun onObremponViewClick(v: View?) {
        when (v!!.id) {
            R.id.buttonDone -> {//提交
                val selectDay = getSelectDay()
                if (selectDay == 0){
                    showObremponToast(context.getString(R.string.obrempon_dialog_tips_select_birth_error))
                    return
                }
                dismiss()
                var formatDay = "$selectDay"
                if (selectDay < 10){
                    formatDay = "0$selectDay"
                }

                val calendar = Calendar.getInstance()
                calendar.set(Calendar.YEAR, showYear)
                calendar.set(Calendar.MONTH, showMonth-1)
                calendar.set(Calendar.DAY_OF_MONTH, selectDay)
                val obj = JSONObject()
                obj.put("showDate","$formatDay-${ObremponDateHelper.getMonthList()[showMonth - 1].optString("month")}-$showYear")
                obj.put("subDate",SimpleDateFormat("yyyy-MM-dd").format(calendar.timeInMillis))
                obj.put("duration",System.currentTimeMillis() - startTime)
                if (mCallback != null){
                    mCallback!!.completed(obj)
                }
            }
        }
    }

    override fun show() {
        super.show()
        startTime = System.currentTimeMillis()
    }

    interface IDialogCallback {
        fun completed(selectDate: JSONObject)
    }

    /**
     * 设置月份
     */
    private fun initBirthdayMonthTabLayout(){
        binding.monthTabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener{
            override fun onTabSelected(tab: TabLayout.Tab?) {
                tab!!.setSelected(tab)
            }
            override fun onTabUnselected(tab: TabLayout.Tab?) {
                tab!!.setUnselected()
            }
            override fun onTabReselected(tab: TabLayout.Tab?) {
            }
        })
    }

    private fun initBirthdayWeekListView() {
        binding.recyclerViewWeek.setHasFixedSize(true)
        binding.recyclerViewWeek.isNestedScrollingEnabled = false
        binding.recyclerViewWeek.isFocusableInTouchMode = false //不需要焦点
//        val decoration = ObremponDensityUtil.dp2px(12f)
//        binding.rvWeek.addItemDecoration(GridSpacingItemDecoration(7,decoration,true))
        val layoutManager = GridLayoutManager(context,7)
        binding.recyclerViewWeek.layoutManager = layoutManager
        weekAdapter = ObremponBirthdayWeekApt(binding.recyclerViewWeek)
        binding.recyclerViewWeek.adapter = weekAdapter
        binding.recyclerViewWeek.itemAnimator = DefaultItemAnimator()
        weekAdapter!!.data = ObremponDateHelper.getWeekList()
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun initBirthdayDayListView() {
        binding.recyclerViewDay.setHasFixedSize(true)
        binding.recyclerViewDay.isNestedScrollingEnabled = false
        binding.recyclerViewDay.isFocusableInTouchMode = false //不需要焦点
        val decoration = ObremponDensityUtil.dp2px(12f)
        binding.recyclerViewDay.addItemDecoration(GridSpacingItemDecoration(7,decoration,true))
        val layoutManager = GridLayoutManager(context,7)
        binding.recyclerViewDay.layoutManager = layoutManager
        dayAdapter = ObremponBirthdayDayApt(binding.recyclerViewDay)
        binding.recyclerViewDay.adapter = dayAdapter
        binding.recyclerViewDay.itemAnimator = DefaultItemAnimator()
        dayAdapter?.setOnItemChildClickListener(ObremponOnItemChildClickListener { _, childView, position ->
            val item = dayAdapter!!.getItem(position)
            if (showYear > ObremponDateHelper.getCurtYear()){
                return@ObremponOnItemChildClickListener
            }
            if (showYear == ObremponDateHelper.getCurtYear() && showMonth > ObremponDateHelper.getCurtMonth()){
                return@ObremponOnItemChildClickListener
            }
            if (showYear == ObremponDateHelper.getCurtYear() && showMonth == ObremponDateHelper.getCurtMonth() && item.optInt("day") > ObremponDateHelper.getCurtDay()){
                return@ObremponOnItemChildClickListener
            }
            if (item.optBoolean("isSelect") || item.optInt("day") == 0){
                return@ObremponOnItemChildClickListener
            }

            for (i in 0..< dayAdapter!!.itemCount){
                val obj = dayAdapter!!.getItem(i)
                obj.put("isSelect",false)
                if (i == position){
                    obj.put("isSelect",true)
                }
            }
            dayAdapter?.notifyDataSetChanged()
        })
    }

    /**
     * 选中状态
     */
    fun TabLayout.Tab.setSelected(tab: TabLayout.Tab) {
        if (showYear > ObremponDateHelper.getCurtYear()){
            return
        }
        this.customView?.let {
            val textMonth = it.findViewById<RobotoMediumTextView>(R.id.textMonth)
            textMonth.typeface = ObremponApp.app.getBoldTypeface()
            textMonth.setTextColor(getColor(R.color.white))
            textMonth.shapeDrawableBuilder.setSolidColor(getColor(R.color.color_ff0569ff)).intoBackground()
        }
        if (!isInit){
            showMonth = tab.position + 1
            showDay()
        }
        isInit = false
    }

    /**
     * 未选中状态
     */
    fun TabLayout.Tab.setUnselected() {
        this.customView?.let {
            val textMonth = it.findViewById<RobotoMediumTextView>(R.id.textMonth)
            textMonth.typeface = ObremponApp.app.getMediumTypeface()
            textMonth.setTextColor(getColor(R.color.black))
            textMonth.shapeDrawableBuilder.setSolidColor(getColor(R.color.transparent)).intoBackground()
        }
    }

    /**
     * 设置年份
     */
    private fun showYear(){
        binding.textYear.text = "$showYear"
    }

    /**
     * 设置月份
     */
    private fun showMonth(){
        binding.monthTabLayout.removeAllTabs()
        val monthList = ObremponDateHelper.getMonthList()
        monthList.forEach {
            it.put("year",showYear)
            val tab = binding.monthTabLayout.newTab()
            val tabBinding = ObremponBirthdayDialogMonthItemBinding.inflate(LayoutInflater.from(context))
            tabBinding.textMonth.text = it.optString("month")
            tab.setCustomView(tabBinding.root)
            binding.monthTabLayout.addTab(tab)
        }

        val curtIndex = showMonth - 1
        binding.monthTabLayout.getTabAt(curtIndex)!!.select()
        binding.monthTabLayout.post {
            binding.monthTabLayout.setScrollPosition(curtIndex,0f,false)
        }
    }

    /**
     * 设置日期
     */
    private fun showDay(){
        val dayList = arrayListOf<JSONObject>()
        //指定年月的1号是星期几
        val week = ObremponDateHelper.getDayOfWeek(showYear,showMonth,1)
        for (i in 0..<week){
            val item  = JSONObject()
            item.put("year",0)
            item.put("month",0)
            item.put("day",0)
            dayList.add(item)
        }
        dayList.addAll(ObremponDateHelper.getDayList(showYear,showMonth))
        for (i in 0..<dayList.size){
            val day = dayList[i]
            day.put("isSelect",false)
            if (showYear == ObremponDateHelper.getCurtYear() && showMonth == ObremponDateHelper.getCurtMonth() && day.optInt("day") == showDay){
                day.put("isSelect",true)
            }
        }
        dayAdapter?.data = dayList
    }

    /**
     * 获取选中的日期
     */
    private fun getSelectDay(): Int{
        var day = 0
        for (i in 0..<dayAdapter!!.itemCount){
            val item = dayAdapter!!.getItem(i)
            if (item.optBoolean("isSelect")){
                day = item.optInt("day")
                break
            }
        }
        return day
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(ObremponEventPointType.DIALOG.OBREMPON_DIALOG_BIRTHDAY_SHOW,eventRemark)
    }

    override fun dismiss() {
        super.dismiss()
        addEventPointRequestAction(ObremponEventPointType.DIALOG.OBREMPON_DIALOG_BIRTHDAY_DISMISS,eventRemark)
    }
}